package com.ants.modules.leavingMessage.controller;

import cn.hutool.core.util.StrUtil;
import com.ants.common.annotation.AutoLog;
import com.ants.common.annotation.RateLimiter;
import com.ants.common.system.query.QueryGenerator;
import com.ants.common.utils.IPUtils;
import com.ants.common.system.result.Result;
import com.ants.modules.leavingMessage.entity.LeavingMessage;
import com.ants.modules.leavingMessage.service.LeavingMessageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * TODO
 * Author Chen
 * Date   2022/8/11 18:44
 */

@Slf4j
@Api(tags = "留言")
@RestController
@RequestMapping("/leavingMessage")
public class LeavingMessageController {

    @Autowired
    LeavingMessageService leavingMessageService;
    @Autowired
    AmqpTemplate rabbitTemplate;

      @RateLimiter
    @AutoLog(value = "留言-列表")
    @ApiOperation(value = "留言-列表", notes = "留言-列表")
    @GetMapping("/list")
    public Result<?> queryPageList(LeavingMessage leavingMessage,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        //String username = StpUtil.getLoginIdAsString();
        QueryWrapper<LeavingMessage> queryWrapper = QueryGenerator.initQueryWrapper(leavingMessage, req.getParameterMap());
        //queryWrapper.eq("create_by", username);
        //queryWrapper.orderByAsc("sort_no/");
        Page<LeavingMessage> page = new Page<LeavingMessage>(pageNo, pageSize);
        IPage<LeavingMessage> pageList = leavingMessageService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param leavingMessage
     * @return
     */
      @RateLimiter
    @AutoLog(value = "留言-添加")
    @ApiOperation(value = "留言-添加", notes = "留言-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody LeavingMessage leavingMessage, HttpServletRequest req) {
        String agentStr = req.getHeader("user-agent");
        UserAgent agent = UserAgent.parseUserAgentString(agentStr);
        String browser = IPUtils.getBrowser(req);
        leavingMessage.setBrowser(browser);
        String ip = IPUtils.getIpAddress(req);
        leavingMessage.setIp(ip);
        String ipAddress = IPUtils.getLocalCityInfo(ip);
        leavingMessage.setIpAddr(ipAddress);
        if (StrUtil.isBlank(leavingMessage.getAvatar())) {
            // 在壁纸中随机抽取一张图片作为 头像
            String avatar = leavingMessageService.getRandomAvatar();
            leavingMessage.setAvatar(avatar);
        }
        OperatingSystem os = agent.getOperatingSystem();
        leavingMessage.setOsName(os.getName());
        leavingMessage.setStatus("0");
        boolean b = leavingMessageService.save(leavingMessage);

        Map<String, String> map = new HashMap<>();
        map.put("name", leavingMessage.getName());
        map.put("message", leavingMessage.getMessage());
        rabbitTemplate.convertAndSend("leavingMessagePushQueue", map);

        if (b) {
            return Result.ok("操作成功!");
        }
        return Result.error("操作失败!");
    }


    /**
     * 编辑
     *
     * @param leavingMessage
     * @return
     */
    @AutoLog(value = "留言-编辑")
    @ApiOperation(value = "留言-编辑", notes = "留言-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody LeavingMessage leavingMessage) {
        boolean b = leavingMessageService.updateById(leavingMessage);

        Map<String, String> map = new HashMap<>();
        map.put("mail", leavingMessage.getMail());
        map.put("status", "1".equals(leavingMessage.getStatus()) ? "审核不通过" : "审核通过");
        map.put("message", leavingMessage.getMessage());
        rabbitTemplate.convertAndSend("leavingMessageCheckQueue", map);
        if (b) {
            return Result.ok("操作成功!");
        }
        return Result.error("操作失败!");
    }

    /**
     * @param id
     * @return
     * @功能：删除
     */
    @DeleteMapping("/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        boolean ok = leavingMessageService.removeById(id);
        if (ok) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }

    /**
     * @param ids
     * @return
     * @功能：批量删除
     */
    @DeleteMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        boolean ok = leavingMessageService.removeByIds(Arrays.asList(ids.split(",")));
        if (ok) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }


}
